import express from 'express';
import multer from 'multer';
import path from 'path';
import fs from 'fs';
import PDFDocument from 'pdfkit';

const router = express.Router();

// 配置 multer 上传
const storage = multer.diskStorage({
  destination: (req, file, cb) => {
    const uploadDir = 'uploads/';
    if (!fs.existsSync(uploadDir)) {
      fs.mkdirSync(uploadDir, { recursive: true });
    }
    cb(null, uploadDir);
  },
  filename: (req, file, cb) => {
    const uniqueSuffix = Date.now() + '-' + Math.round(Math.random() * 1E9);
    cb(null, file.fieldname + '-' + uniqueSuffix + path.extname(file.originalname));
  }
});

const upload = multer({ storage });

// 上传云数据
router.post('/cloud-data', upload.single('file'), (req, res) => {
  if (!req.file) {
    return res.status(400).json({ error: '没有上传文件' });
  }
  
  res.json({
    success: true,
    message: '云数据上传成功',
    file: {
      filename: req.file.filename,
      originalname: req.file.originalname,
      size: req.file.size,
      path: req.file.path
    }
  });
});

// 生成 PDF 报告
router.post('/generate-pdf', (req, res) => {
  const { reportData } = req.body;
  
  if (!reportData) {
    return res.status(400).json({ error: '缺少报告数据' });
  }
  
  const doc = new PDFDocument();
  const filename = `report-${Date.now()}.pdf`;
  const filepath = `uploads/${filename}`;
  
  doc.pipe(fs.createWriteStream(filepath));
  
  // 报告标题
  doc.fontSize(20).text('智觅免忧 miRNA 检测报告', { align: 'center' });
  doc.moveDown();
  
  // 患者信息
  doc.fontSize(14).text('患者信息', { underline: true });
  doc.fontSize(12).text(`患者ID: ${reportData.patientId}`);
  doc.text(`检测盒ID: ${reportData.boxId}`);
  doc.text(`批次号: ${reportData.batchNumber}`);
  doc.text(`检测日期: ${reportData.testDate}`);
  doc.moveDown();
  
  // 检测结果
  doc.fontSize(14).text('检测结果', { underline: true });
  doc.fontSize(12).text(`miR-193a-5p 水平: ${reportData.mir193a5pLevel}`);
  doc.text(`置信度: ${reportData.confidenceScore}%`);
  doc.text(`分析时间: ${reportData.analysisTime}分钟`);
  doc.text(`临床精度: ${reportData.clinicalAccuracy}`);
  doc.moveDown();
  
  // 结论
  doc.fontSize(14).text('检测结论', { underline: true });
  doc.fontSize(12).text('基于AI算法分析，检测结果符合临床标准。');
  doc.text('建议结合临床症状进行综合评估。');
  
  doc.end();
  
  res.json({
    success: true,
    message: 'PDF报告生成成功',
    filename,
    downloadUrl: `/uploads/${filename}`
  });
});

// 下载文件
router.get('/download/:filename', (req, res) => {
  const { filename } = req.params;
  const filepath = path.join(process.cwd(), 'uploads', filename);
  
  if (!fs.existsSync(filepath)) {
    return res.status(404).json({ error: '文件不存在' });
  }
  
  res.download(filepath);
});

export default router;